package com.ukao.cashregister.ui.createOrders;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.ukao.cashregister.R;
import com.ukao.cashregister.base.MvpFragment;
import com.ukao.cashregister.bean.ClothginQuiryBean;
import com.ukao.cashregister.bean.ReadBean;
import com.ukao.cashregister.bean.UserInfoBean;
import com.ukao.cashregister.eventbus.MembershipCardEvent;
import com.ukao.cashregister.pesenter.CreateOrdersPesenter;
import com.ukao.cashregister.rfid.MembershipCardHelper;
import com.ukao.cashregister.ui.clothinQuery.ClothingDetailsFragment;
import com.ukao.cashregister.ui.vipManager.CreateVipFragment;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.RegularUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.view.CreateOrdersView;

import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.consts.GlobalConsts.CLOTHING_QUIRY;
import static com.ukao.cashregister.consts.GlobalConsts.CREATE_ORDERS;
import static com.ukao.cashregister.consts.GlobalConsts.CREATE_USER;
import static com.ukao.cashregister.consts.GlobalConsts.PICK_CLOTHING;

/**
 * 下单
 * Created by ukaodev on 2017/5/17.
 */
public class CreateOrdersFragment extends MvpFragment<CreateOrdersPesenter> implements CreateOrdersView {
    @BindView(R.id.fragment_create_orders_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.fragment_create_orders_radio_group)
    RadioGroup mRadioGroup;
    @BindView(R.id.fragment_create_orders_edit)
    EditText mEdit;
    @BindView(R.id.fragment_create_orders_go)
    Button mBtnGo;
    @BindView(R.id.fragment_create_orders_tips)
    TextView mTextTips;
    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.fragment_create_orders_submit)
    Button mBtnSubmit;
    @BindView(R.id.fragment_create_orders_tab1_layout)
    LinearLayout mTab1Layout;
    @BindView(R.id.fragment_create_orders_tab1)
    RadioButton mBtnorders;
    @BindView(R.id.fragment_create_orders_tab2_layout)
    LinearLayout mTab2Layout;
    @BindView(R.id.fragment_create_orders_tab2)
    RadioButton mCardBtn;
    Unbinder unbinder;
    @BindView(R.id.read_error_fail)
    TextView readErrorFail;
    private String classType = "";

    private String describe;
    private String phone;
    private String hite;
    private String title;
    private Handler mHandler = new Handler();
    private  boolean isNfcReadCard=false;
    public static CreateOrdersFragment newInstance(String param1, String param2, String param3) {
        CreateOrdersFragment fragment = new CreateOrdersFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(ARG_PARAM3, param3);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            title = getArguments().getString(ARG_PARAM2);
            classType = getArguments().getString(ARG_PARAM1);
            hite = getArguments().getString(ARG_PARAM3, "");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_create_orders, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);

    }




    @Override
    protected CreateOrdersPesenter createPresenter() {
        return new CreateOrdersPesenter(this);
    }


    @Override
    protected void initView() {
        mTitle.setText(title);
        mBtnorders.setText(hite);
        mEdit.setHint(hite);
        mBtnSubmit.setVisibility(View.GONE);
        mEdit.requestFocus();
        showSoftInput(mEdit);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mEdit.setOnEditorActionListener(mOnEditorAction);
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }


    @Subscribe
    public void onEvent(MembershipCardEvent event) {
        switch (event.getMessage()) {
            case add:/*成功*/
                if (!isVisible)return;
                String userId =(String)event.getData();
                mvpPresenter.rfidSecret(userId);
                break;
            case fali:/*读卡失败*/
                if (!isVisible)return;
                String  error=(String)event.getData();
                readErrorFail.setText(error);
                postDelayedReadCard();
                break;
            case notFound:/*没有卡*/
                if (!isVisible)return;
                postDelayedReadCard();
                break;
            case   nfc_read:  /*商米NFC读卡*/
                if (isNfcReadCard&&mCardBtn.isChecked()){
                    String  nfcUseid=(String)event.getData();
                    mvpPresenter.rfidSecret(nfcUseid);
                }
                break;
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        postDelayedReadCard();
    }

    TextView.OnEditorActionListener mOnEditorAction = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {
                gotoRequest();
            }
            return false;
        }
    };
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        MembershipCardHelper.getInstance().onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    @OnClick({R.id.fragment_create_orders_go, R.id.fragment_create_orders_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fragment_create_orders_go:
                gotoRequest();
                break;
            case R.id.fragment_create_orders_submit:  //创建该账户
                isNfcReadCard=false;
                startForResult(CreateVipFragment.newInstance(getText(mEdit)),CREATE_USER);
                break;
        }
    }
    public void gotoRequest() {
        phone = getText(mEdit);
        if (phone.isEmpty()) {
            T.show("请填写" + hite);
            return;
        }

        hideSoftInput();
        typeRequest(phone);
    }

    private void typeRequest(String  phone) {
        switch (classType) {
            case CREATE_ORDERS: /*下单*/
                mvpPresenter.placeOrderData(_mActivity, phone);
                break;
            case PICK_CLOTHING:/*取衣*/
                mvpPresenter.takeUserClothing(_mActivity, phone);
                break;
            case CLOTHING_QUIRY: /*衣物详情*/
                mvpPresenter.clothginQuirydetail(_mActivity, phone);
                break;
        }
    }

    @Override
    protected void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CREATE_USER:
                  String  phone=data.getString("phone");
                    if (!CheckUtils.isEmpty(phone)){
                        mEdit.setText(phone);
                        mvpPresenter.placeOrderData(_mActivity, phone);
                    }
                    break;
            }
        }

    }

    @OnCheckedChanged({R.id.fragment_create_orders_tab1, R.id.fragment_create_orders_tab2})
    public void onCheckedChanged(CompoundButton buttonView, boolean checked) {
        //防止重复响应点击
        mRadioGroup.clearCheck();
        switch (buttonView.getId()) {
            case R.id.fragment_create_orders_tab1:
                mTab1Layout.setVisibility(View.VISIBLE);
                mTab2Layout.setVisibility(View.GONE);
                break;
            case R.id.fragment_create_orders_tab2:
                postDelayedReadCard();
                mTab1Layout.setVisibility(View.GONE);
                mTab2Layout.setVisibility(View.VISIBLE);
                break;
        }
    }



    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        isVisible=false;
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        isNfcReadCard=true;
        isVisible=true;
        postDelayedReadCard();
    }

    /**
     * 读卡
     */
    private void postDelayedReadCard() {
        mHandler.removeCallbacksAndMessages(null);
        if (!isVisible)return;
        if (!mCardBtn.isChecked())return;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                L.i("读卡");
                MembershipCardHelper.getInstance().readUserId();
            }
        }, 1500);
    }
    @Override
    public void loadOrderSuccess(UserInfoBean model,String  searchValue) {
        isNfcReadCard=false;
        UserInfoBean mData = model.getData();
        if (CheckUtils.isNull(mData)) {
            if (RegularUtils.isMobileSimple(searchValue)){
                T.show("该手机账户不存在，请创建账户");
                mBtnSubmit.setVisibility(View.VISIBLE);
            }else{
                mBtnSubmit.setVisibility(View.GONE);
                T.show("该会员卡号不存在");
            }
        } else {   //当前页面读卡成功 就会跑这里的代码
            mBtnSubmit.setVisibility(View.GONE);
            mData.setSearchValue(searchValue);
            start(UserInfoFragment.newInstance(classType, mData),SINGLETASK);
        }


    }


    @Override
    public void loadFail(String model) {
        T.show(model);
    }

    @Override
    public void loadRfrdSuccess(ReadBean model) {
        typeRequest(model.getData().getPhone());
    }

    @Override
    public void loadClothingSuccess(ClothginQuiryBean model,String  searchValue) {
        isNfcReadCard=false;
        model.setClothingSearchValue(searchValue);
        start(ClothingDetailsFragment.newInstance(model), SINGLETASK);
    }






}
